package cool.webstudy.admin.utils.aspect.permissions;

import cool.webstudy.admin.constant.enums.RoleEnum;
import cool.webstudy.admin.constant.enums.rescode.CommonResCodeEnum;
import cool.webstudy.admin.exception.BusinessException;
import cool.webstudy.admin.model.dto.user.UserDetailInfoDTO;
import cool.webstudy.admin.utils.UserDetailUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 莫振双
 * @date 2025/3/23 1:03
 * @description: 权限校验切面
 */
@Aspect
@Component
@Slf4j
public class PermissionsCheckAspect {
    /**
     * 以方法或类上自定义的注解@PermissionsCheck为切入点
     * 其中@annotation匹配方法上的注解；@within匹配类上的注解
     */
    @Pointcut("@annotation(PermissionsCheck) || @within(PermissionsCheck)")
    public void controllerMethods() {
    }

    @Before("controllerMethods()")
    public void checkPermissions(JoinPoint joinPoint) {
        // 获取被拦截的方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取目标方法
        Method method = signature.getMethod();
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        // 获取 @PermissionsCheck 注解
        PermissionsCheck permissionsCheck = method.getAnnotation(PermissionsCheck.class);
        // 获取 role 属性值
        RoleEnum role = permissionsCheck.role();
        // 判断当前用户是否具有权限
        if (!role.getRole().equals(userDetailInfo.getRole().getRole())){
            //如果权限不一致，则抛出异常
            throw new BusinessException(CommonResCodeEnum.RC_ERROR_PERMISSION);
        }
    }
}
